package com.dave.admin.config.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dave.admin.config.auth.pojo.BossUserDetails;
import com.dave.admin.modular.boss.entity.Permission;
import com.dave.admin.modular.boss.entity.UserAdmin;
import com.dave.admin.modular.boss.service.IUserAdminService;
import com.dave.admin.modular.boss.service.IPermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 自定义用户读取方式
 * @author Dave
 */
@Service
public class BossUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(BossUserDetailsService.class);

    @Autowired
    private IUserAdminService userAdminService;

    @Autowired
    private IPermissionService iPermissionService;

    /**
     * 获取登录用户信息
     */
    @Override
    @Cacheable(value = "user#1m", key = "#username")
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserAdmin userAdmin = userAdminService.getOne(new QueryWrapper<UserAdmin>().eq(UserAdmin.USERNAME, username));
        if (Objects.nonNull(userAdmin)) {
            //相关权限
            List<Permission> permissionList = iPermissionService.permissionList(userAdmin.getId());
            return new BossUserDetails(userAdmin, permissionList);
        }
        logger.warn("该账号不存在{}", username);
        throw new UsernameNotFoundException("账号不存在");
    }
}
